package cn.chencq.utils;

import java.io.IOException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.alibaba.druid.util.StringUtils;

public class ProxyIpUtils {

	private static final Logger logger = LoggerFactory.getLogger(ProxyIpUtils.class);

	/**
	 * 判断ip和端口是否有效
	 * 
	 * @param ip
	 * @param port
	 * @return
	 */
	public static boolean checkProxy(String ip, Integer port) {
		try {
			Document doc = Jsoup.connect("http://2019.ip138.com/ic.asp").timeout(2 * 1000).proxy(ip, port).get();
			logger.info("ip:{}, port:{}, ip138查询结果:{}", ip, port, doc.select("center").html());
			return true;
		} catch (Exception e) {
			return false;
		}
	}

	public static String getServerIp() {
		Document doc = null;
		String ip = null;
		try {
			doc = Jsoup.connect("http://2019.ip138.com/ic.asp").timeout(2 * 1000).get();
			String text = doc.select("center").html();
			if (StringUtils.isEmpty(text)) {
				return ip;
			}
			String regex = "((25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]\\d|\\d)\\.){3}(25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]\\d|[1-9])";
			Pattern p = Pattern.compile(regex);
			Matcher m = p.matcher(text);
			while (m.find()) {
				ip = m.group();
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
		return ip;
	}

}
